//
//  OCDeviceService.m
//  VideoTeleprompter
//
//  Created by Duncan on 2021/4/16.
//

#import "OCDeviceService.h"
#import <AVKit/AVKit.h>

@implementation OCDeviceService

+ (instancetype)share {
    static OCDeviceService *service = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        service = [[self alloc] init];
    
    });
    return service;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

/// 跳转app系统设置
+ (void)openUIApplicationOpenSettingsURLString {
    NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    }
}

/// 跳转App Store评论
+ (void)openUIApplicationWriteReviewString {
    NSString *nsStringToOpen = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%d?action=write-review", kAppStoreAppID.intValue];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsStringToOpen] options:@{} completionHandler:nil];
}

/// 提示没有相册权限
+ (void)showTipsWithPhotosRequestAuthorization {
    [TSHandleAlertView showSystemAlertViewMessage:@"需要打开相册选择图片，若需开启相册权限可以点击确定前往" OKHandler:^(UIAlertAction * _Nonnull action) {
        [OCDeviceService openUIApplicationOpenSettingsURLString];
    }];
}

/// 系统分享链接
+ (void)shareWithUrlStiring:(NSString *)urlString {
    NSString *textToShare = [UIDevice appName];
    UIImage *imageToShare = [UIImage imageNamed:@"base_laolaile_icon"];
    NSArray *activityItems = @[textToShare, imageToShare, [NSURL URLWithString:urlString]];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    activityVC.excludedActivityTypes = @[UIActivityTypePrint,
                                         UIActivityTypeCopyToPasteboard,
                                         UIActivityTypeAssignToContact,
                                         UIActivityTypeSaveToCameraRoll];
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        
    } else {
        activityVC.popoverPresentationController.sourceView = [UIApplication currentViewController].view;
        activityVC.popoverPresentationController.sourceRect = CGRectMake(kScreen_Width / 2, kScreen_Height / 2, 1, 1);
        activityVC.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
    }
    
    [[UIApplication currentViewController] presentViewController:activityVC animated:YES completion:nil];
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            [OCProgress_HUD showSuccessWithStatus:@"分享成功"];
        }
    };
}

/// 系统分享文件
+ (void)shareWithFileStiring:(NSString *)fileString {
    NSArray *activityItems = @[[[NSURL alloc] initFileURLWithPath:fileString]];

    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    activityVC.excludedActivityTypes = @[UIActivityTypePrint,
                                         UIActivityTypePostToWeibo,
                                         UIActivityTypeCopyToPasteboard,
                                         UIActivityTypeAddToReadingList,
                                         UIActivityTypePostToVimeo,
                                        ];
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        
    } else {
        activityVC.popoverPresentationController.sourceView = [UIApplication currentViewController].view;
        activityVC.popoverPresentationController.sourceRect = CGRectMake(kScreen_Width / 2, kScreen_Height / 2, 1, 1);
        activityVC.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp;
    }
    
    [[UIApplication currentViewController] presentViewController:activityVC animated:YES completion:nil];
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            [OCProgress_HUD showSuccessWithStatus:@"分享成功"];
        }
    };
}

/// 打开QQ聊天界面
+ (void)openQQWithQQNumber:(NSString *)qqNumber {
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
        NSString *qq = [NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web", qqNumber];
        NSURL *url = [NSURL URLWithString:qq];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    } else {
        [TSHandleAlertView showSystemAlertViewMessage:qqNumber title:@"请加QQ"];
    }
}

/// 添加QQ群
+ (void)addQQGroupWithNumber:(NSString *)number {
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
        NSString* urlStr = [NSString stringWithFormat:@"mqqapi://card/show_pslcard?src_type=internal&version=1&uin=%@&key=%@&card_type=group&source=external", number, @"d2b26edf701959915753245605d87e415506cd38e20211d32eb4d43a6106c3c0"];
        NSURL *url = [NSURL URLWithString:urlStr];
         if ([[UIApplication sharedApplication] canOpenURL:url]) {
             [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
         }

    } else{
        [TSHandleAlertView showSystemAlertViewMessage:number title:@"请加QQ群" okTitle:@"复制" cancelTitle:@"取消" OKHandler:^(UIAlertAction * _Nullable action) {
            [OCDeviceService copyWithString:number];
        }];
    }
}

/// 复制字符串
+ (void)copyWithString:(NSString *)string {
    if (string.length > 0) {
        UIPasteboard *pab = [UIPasteboard generalPasteboard];
        pab.string = string ?: @"";
        [OCProgress_HUD showSuccessWithStatus:@"复制成功"];
    }
}

/// 震动
+ (void)feedbackGenerator {
    UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
    [generator prepare];
    [generator impactOccurred];
}

#pragma mark ------- txt -------

/// 导出txt
+ (void)daochuTxtWithString:(NSString *)content {
    if (content.length <= 0) {
        [OCProgress_HUD showErrorWithStatus:@"内容为空!"];
        return;
    }
    NSURL *toUrl = [NSURL exporterPathString:kOCNormalPathString filename:@"txt"];
    
    NSError *error;
    [FCFileManager writeFileAtPath:toUrl.path content:content error:&error];
    if (error == nil) {
        DEBUGLOG(@"生成成功");
        [OCDeviceService shareWithFileStiring:toUrl.path];
        
    } else {
        DEBUGLOG(@"生成失败 %@", error);
    }
}

/// 提取txt文件内容
+ (NSString *)extractTextContentWithFilePaht:(NSString *)filePath {
    
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    
    NSData * data = [NSData dataWithContentsOfFile:filePath];
    NSString * chapterContent = @"";
    BOOL lossy = NO;
    NSArray * enccList = @[@(NSUTF8StringEncoding), @(enc)];
    NSStringEncoding encc = [NSString stringEncodingForData:data
                                            encodingOptions:@{NSStringEncodingDetectionSuggestedEncodingsKey:enccList}
                                            convertedString:&chapterContent  usedLossyConversion:&lossy];
    DEBUGLOG(@"encc===%ld", encc);
    DEBUGLOG(@"chapterContent ===%@", chapterContent);
    
    return chapterContent;
}

#pragma mark ------- 保存图片 -------

/// 保存图片
- (void)saveImageToAlbumWithNameimage:(UIImage *)image {
    //判断授权状态
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusAuthorized) { //已授权
        [self saveImageWithImage:image albumName:[UIDevice appName]];
    } else if (status == PHAuthorizationStatusDenied) { //拒绝
        DEBUGLOG(@"请打开访问相册的权限");
        [TSHandleAlertView showSystemAlertViewMessage:@"请打开访问相册的权限" title:nil];
    } else if (status == PHAuthorizationStatusNotDetermined) { //未决定
        // 弹框请求用户授权
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status == PHAuthorizationStatusAuthorized) { // 用户点击了好
                [self saveImageWithImage:image albumName:[UIDevice appName]];
            }
        }];
    } else if (status == PHAuthorizationStatusRestricted) { //家长控制模式限制
        DEBUGLOG(@"因为系统原因, 无法访问相册");
        [OCProgress_HUD showErrorWithStatus:@"因为系统原因, 无法访问相册"];
    }
}

- (PHAssetCollection *)creatPHAssetWithAlbumName:(NSString *)albumName {
    
    //从已经存在的相簿中查找应用对应的相册
    PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in assetCollections) {
        if ([collection.localizedTitle isEqualToString:albumName]) {
            return collection;
        }
    }
    // 没找到，就创建新的相簿
    NSError *error;
    __block NSString *assetCollectionLocalIdentifier = nil;
    //这里用wait请求，保证创建成功相册后才保存进去
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{

        assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName].placeholderForCreatedAssetCollection.localIdentifier;
        
    } error:&error];
    
    if (error) return nil;
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;
}

- (void)saveImageWithImage:(UIImage *)image albumName:(NSString *)albumName {
    // PHAsset : 一个资源，一个图片
    // PHAssetCollection : 一个相簿 （也可以说是一个相册）
    // PHotoLibrary 整个照片库（里面会有很多相册）
    
    __block NSString *assetLocalIdentifier = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        
        // 1.保存图片到相机胶卷中
        assetLocalIdentifier = [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        if (success == NO || error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                DEBUGLOG(@"保存照片失败");
                [OCProgress_HUD showErrorWithStatus:@"保存照片失败"];
            });
            return;
        }
        
        // 2. 获得相册
        PHAssetCollection *creatAssetCollction = [self creatPHAssetWithAlbumName:albumName];
        if (creatAssetCollction == nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                DEBUGLOG(@"创建相册失败");
                [OCProgress_HUD showErrorWithStatus:@"创建相册失败"];
            });
            return;
        }
        
        //创建成功，就把图片保存到相册中
        [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
            
            //添加相机胶卷中的图片到相簿中去
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
            //添加图片到相册中的请求
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:creatAssetCollction];
            [request addAssets:@[asset]];
            
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            
            if (success == NO || error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    DEBUGLOG(@"保存图片失败");
                    [OCProgress_HUD showErrorWithStatus:@"保存图片失败"];
                });
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    DEBUGLOG(@"保存图片成功");
                    [OCProgress_HUD showSuccessWithStatus:@"保存图片成功"];
                });
            }
        }];
    }];
}

/// 保存gif图
- (BOOL)savedToPhotosAlbum:(NSString *)path {
    
    __block NSString *createdAssetID = nil;//唯一标识，可以用于图片资源获取
    NSError *error = nil;
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        createdAssetID = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:[NSURL fileURLWithPath:path]].placeholderForCreatedAsset.localIdentifier;
    } error:&error];
    
    return createdAssetID && !error;
}

#pragma mark ------- 视频保存到相册 -------

/// 本地视频保存到相册
- (void)saveVideoWithVideoPath:(NSString *)videoPath handle:(void(^)(BOOL success, NSError *error))saveHandle {
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL fileURLWithPath:videoPath]];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        saveHandle(success,error);
    }];
}

/// 保存网络视频到相册
- (void)saveNetworkingVideoWithString:(NSString *)urlString handle:(void(^)(BOOL success, NSError *error))saveHandle {
    
    kWEAKSELF
    NSURLRequest *requset = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

    //返回一个下载任务对象
    [OCProgress_HUD show];
    
    NSURLSessionDownloadTask *loadTask = [[NetworkService service].manager downloadTaskWithRequest:requset progress:^(NSProgress * _Nonnull downloadProgress) {
        // completedUnitCount 下载的大小 totalUnitCount文件的总大小
        NSLog(@"%lld----%lld", downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
        [OCProgress_HUD showProgress:downloadProgress.fractionCompleted];
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        // 需先创建文件夹
        NSString *fullPath = kOCNormal_Appending(response.suggestedFilename);
        DEBUGLOG(@"targetPath-：%@---fullPath:-%@", targetPath, fullPath);
        
        NSURL *toUrl = [NSURL fileURLWithPath:fullPath];
        
        NSString *pathExtension = toUrl.path.pathExtension;
        if (pathExtension.length == 0) {
            fullPath = [NSString stringWithFormat:@"%@.mp4", fullPath];
            toUrl = [NSURL fileURLWithPath:fullPath];
        }
        
        DEBUGLOG(@"targetPath-：%@---fullPath:-%@", targetPath, fullPath);
        // 这个block 需要返回一个目标 地址 存储下载的文件
        return  toUrl;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        NSString *filePathString = filePath.path;
        DEBUGLOG(@"下载完成地址:%@ -- %@", filePath, filePathString);
        [weakSelf saveVideoWithVideoPath:filePathString handle:saveHandle];
        
    }];
    [loadTask resume];
}

/// 获取视频的首帧图片
- (UIImage *)getVideoFirstImageWith:(NSString *)videoString {
    NSURL *url = [NSURL URLWithString:videoString];
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
    if (!asset) {
        return nil;
    }
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    generator.appliesPreferredTrackTransform = YES;
    generator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CFTimeInterval time = 0.1;
    CGImageRef imageRef = [generator copyCGImageAtTime:CMTimeMake(time, 60) actualTime:NULL error:nil];
    UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return image;
}

- (UIImage *)getVideoThumbnailForPath:(NSString *)path {
    AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:path]];
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;

//    CMTime time = CMTimeMakeWithSeconds(0.0, preferredTimescale: 600);
    CMTime time = CMTimeMake(0.1, 60);
    NSError *error = nil;
    CGImageRef imageRef = [assetImageGenerator copyCGImageAtTime:time actualTime:NULL error:&error];
    if (error) {
        NSLog(@"Error generating thumbnail: %@", error);
        return nil;
    }
    UIImage *image = [UIImage imageWithCGImage:imageRef];
    return image;
}

#pragma mark ------- 播放视频 -------

- (void)avPlayWithUrl:(NSURL *)url {
    AVPlayer *avPlayer = [[AVPlayer alloc] initWithURL:url];
    AVPlayerViewController *avPlayerVC = [[AVPlayerViewController alloc] init];
    avPlayerVC.entersFullScreenWhenPlaybackBegins = YES; // 开启这个播放的时候支持（全屏）横竖屏哦
    avPlayerVC.exitsFullScreenWhenPlaybackEnds = YES; // 开启这个所有 item 播放完毕可以退出全屏
    avPlayerVC.player = avPlayer;
    [avPlayerVC.player play];
    [[UIApplication currentViewController] presentViewController:avPlayerVC animated:YES completion:nil];
}

@end
